package com.ruoyi.attendance.controller;

import com.ruoyi.attendance.utils.BaiduFaceMatchUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author: @Weiney
 * @ClassName: FaceRecognitionController
 * @Description: 人脸对比接口
 * @Create: 2025-03-08
 **/

@RestController
@RequestMapping("/face")
@Api(tags = "人脸对比接口")
public class FaceRecognitionController {

    @Autowired
    private BaiduFaceMatchUtil baiduFaceMatchUtil;

    @PostMapping("/match")
    @PreAuthorize("@ss.hasPermi('attendance:sign:face')")
    @ApiOperation("人脸对比")
    public String faceMatch(@RequestParam("signPhoto") MultipartFile signPhoto,
                            @RequestParam("avatarPhoto") MultipartFile avatarPhoto) throws IOException {
        // 将实时上传的拍照照片转换为 Base64 编码
        String livePhoto = baiduFaceMatchUtil.imageToBase64(signPhoto.getBytes());
        // 将用户头像照片转换为 Base64 编码
        String originalPhoto = baiduFaceMatchUtil.imageToBase64(avatarPhoto.getBytes());

        // 调用百度人脸对比 API 进行对比
        return baiduFaceMatchUtil.faceMatch(originalPhoto, livePhoto);
    }
    // 用于测试
    @PostMapping("/testmatch")
    @ApiOperation("人脸对比测试")
    public String testFaceMatch() throws IOException {

        // 本地实时拍照照片的文件路径，请替换为实际路径
        String livePhotoPath = "D:\\env\\123.png";
        // 本地用户头像照片的文件路径，请替换为实际路径
        String originalPhotoPath = "D:\\env\\123.png";

        // 读取实时拍照照片并转换为字节数组
        byte[] livePhotoBytes = readFileToByteArray(livePhotoPath);
        // 读取用户头像照片并转换为字节数组
        byte[] originalPhotoBytes = readFileToByteArray(originalPhotoPath);

        // 将实时上传的拍照照片转换为 Base64 编码
        String livePhotoBase64 = baiduFaceMatchUtil.imageToBase64(livePhotoBytes);
        // 将用户头像照片转换为 Base64 编码
        String originalPhotoBase64 = baiduFaceMatchUtil.imageToBase64(originalPhotoBytes);

        // 调用百度人脸对比 API 进行对比
        return baiduFaceMatchUtil.faceMatch(originalPhotoBase64, livePhotoBase64);
    }
    private byte[] readFileToByteArray(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] buffer = new byte[(int) file.length()];
        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(buffer);
        }
        return buffer;
    }
}